/*
 * Copyright (C) 2012 www.amsoft.cn
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.anysoft.camera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;

import com.anysoft.R;
import com.anysoft.camera.zxing.CameraManager;
import com.anysoft.camera.zxing.CaptureActivityHandler;
import com.anysoft.camera.zxing.Config;
import com.anysoft.camera.zxing.InactivityTimer;
import com.anysoft.camera.zxing.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import java.util.Vector;


//这个类是扫描二维码的,扫码成功后返回扫码结果
//zxing里面都是二维码扫码的代码
public class CaptureActivity extends Activity implements Callback {

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private Button btn_cancel_qr_code;
//    ScanBean response;
//    private CMBLoadingDialog cLoadingDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.qr_code);
        
        CameraManager.init(getApplication());
        btn_cancel_qr_code = (Button) findViewById(R.id.btn_cancel_qr_code);
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        findViewById(R.id.lift_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        cLoadingDialog = new CMBLoadingDialog(this);
        resume();
        viewfinderView.setViewLoadEnd(new ViewfinderView.ViewLoadEnd() {
            @Override
            public void viewLoadSuccess(int frameLeft,int frameBottom) {

                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) btn_cancel_qr_code.getLayoutParams();
                params.topMargin = frameBottom+50;
                params.leftMargin = frameLeft;
                params.rightMargin = frameLeft;
                btn_cancel_qr_code.setText("取消");
                btn_cancel_qr_code.setLayoutParams(params);
//                showToast("bottom:"+frameBottom);
            }
        });
        btn_cancel_qr_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        resume();
    }

//    public void showProgress() {
////        cLoadingDialog.dismiss();
////        if (!isFinishing()) {
////            cLoadingDialog.show();
////        }
//        showToast("对话框showProgress");
//    }

//    public void dissmissProgress() {
//        cLoadingDialog.dismiss();
//    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("onResume", "onResume");
        //resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pause();
    }

    public void pause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    public void resume() {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        //initBeepSound();
        vibrate = true;
    }


    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            int cameraId = 0;
            int orientation = 1;
            Config.cameraId = cameraId;
            Config.orientation = orientation;
            CameraManager.get().openDriver(surfaceHolder, cameraId);
        } catch (Exception e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    public void handleDecode(final Result obj, Bitmap barcode) {
        inactivityTimer.onActivity();
//        playBeepSoundAndVibrate();
        pause();

        goscan(obj.getText());

    }



    private void goscan(String result) {
//        showToast("qrCode"+result);
        Intent intent = new Intent();
        intent.putExtra("result",result);
        setResult(RESULT_OK,intent);
        finish();
    }


//    private void showToast(String message) {
//        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
//    }


    private static final long VIBRATE_DURATION = 200L;

//    private void playBeepSoundAndVibrate() {
//        //领导说哔的声音吓人 不要了
////        if (playBeep && mediaPlayer != null) {
////            mediaPlayer.start();
////        }
//        if (vibrate) {
//            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//            vibrator.vibrate(VIBRATE_DURATION);
//        }
//    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
//    private final OnCompletionListener beepListener = new OnCompletionListener() {
//        public void onCompletion(MediaPlayer mediaPlayer) {
//            mediaPlayer.seekTo(0);
//        }
//    };


}